//
//  ParamsTool.m
//  AppShellTool
//
//  Created by IOS01 on 2022/12/8.
//

#import "ParamsTool.h"
#import "SocketClient.h"

#define kUserKey  @"userInfo"
#define kPemissionKey @"pemissions"
#define kSchemeKey  @"scheme"

@implementation ParamsTool

//name: url中的参数名称
+ (NSString *)getParamByName:(NSString *)name URLString:(NSString *)url {

    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)", name];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
     
    // 执行匹配的过程
    NSArray *matches = [regex matchesInString:url
                                      options:0
                                        range:NSMakeRange(0, [url length])];
    for (NSTextCheckingResult *match in matches) {
        NSString *tagValue = [url substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        return tagValue;
    }
    return @"";
}

+ (void)user:(NSString *)user psw:(NSString *)psw token:(NSString *)token enterpise:(NSString *)enterprise scheme:(NSString *)scheme{
    NSDictionary *dict = @{
        @"user":user?user:@"",
        @"password":psw?psw:@"",
        @"token":token?token:@"",
        @"enterpise":enterprise?enterprise:@"",
    };
    NSDictionary *userInfo = @{kUserKey:dict,kSchemeKey:scheme?scheme:@""};
    NSString *json = [self objectToJSon:userInfo];
    
    //发给外壳
    [[SocketClient shareClient] sendMsg:json];
}


+ (void)appMenuPemissions:(NSArray *)array  scheme:(NSString *)scheme{
    NSDictionary *pemissions = @{kPemissionKey:array,kSchemeKey:scheme?scheme:@""};
    NSString *json = [self objectToJSon:pemissions];
    //发给外壳
    [[SocketClient shareClient] sendMsg:json];
}

/// 字典转字符串
/// @param object 待转的字典
+ (NSString *)objectToJSon:(id)object{
    
    NSError *err = nil;
    if (object == nil) {
        return @"";
    }
    
    NSData *data = [NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:&err];
    NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    if (err) {
        return @"";
    }
    return jsonStr;
}

@end
